import subprocess
from time import sleep

def run_adb_command(ip, port, command_args):
    connect_command = f'adb connect {ip}:{port}'

    """运行ADB命令"""
    base_command = ['adb', '-s', f'{ip}:{port}']
    full_command = base_command + command_args
    try:
        subprocess.run(connect_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        result = subprocess.run(full_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        return result
    except subprocess.CalledProcessError as e:
        print("An error occurred:", e.stderr)
        return None

def check_app_installed(ip, port, package_name):
    try:
        # 使用 adb 命令检查应用程序包是否已安装
        result = run_adb_command(ip, port, ["shell", "pm", "list", "packages", package_name])
        # 检查输出是否包含指定的包名
        return package_name in result.stdout
    except subprocess.CalledProcessError as e:
        print(f"错误: 无法检查应用程序是否安装: {e}")
        return False

def uninstall_app(device_ip, device_port, package_name):
    if check_app_installed(device_ip, device_port, package_name):
        try:
            result = run_adb_command(device_ip, device_port, ['uninstall', package_name])
            print(f"{device_ip}:{device_port} - 应用程序 {package_name} 已成功卸载")
        except subprocess.CalledProcessError as e:
            print(f"卸载失败: {e.stderr}")
    else:
        print(f"{device_ip}:{device_port} - 应用程序 {package_name} 未安装")

if __name__ == '__main__':
    # 定义设备的IP地址和端口列表
    ip = "36.212.131.204"
    port_list = [
        "40045",
        "40066"
    ]

    # 抖音的包名
    package_name = 'com.ss.android.ugc.aweme'

    # 遍历每个端口并尝试卸载应用程序
    for port in port_list:
        print(f"处理设备 {ip}:{port}...")
        uninstall_app(ip, port, package_name)
        sleep(2)  # 等待2秒，防止请求过于频繁